package com.ccteam.admin.viewmodels.common

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import androidx.paging.map
import com.ccteam.admin.api.AlbumAdminDataSource
import com.ccteam.admin.api.ArtistAdminDataSource
import com.ccteam.admin.core.AdminCore
import com.ccteam.admin.domain.AlbumPagingSource
import com.ccteam.admin.domain.ArtistPagingSource
import com.ccteam.admin.view.bean.SelectInfo
import com.ccteam.admin.view.fragments.common.SelectFragment.Companion.SELECT_ALBUM
import com.ccteam.admin.view.fragments.common.SelectFragment.Companion.SELECT_ARTIST
import com.ccteam.admin.view.fragments.common.SelectFragment.Companion.SELECT_MUSIC
import com.ccteam.model.album.AlbumVO
import com.ccteam.model.artist.ArtistVO
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/2
 */
@HiltViewModel
class SelectViewModel @Inject constructor(
    private val adminCore: AdminCore,
    private val artistAdminDataSource: ArtistAdminDataSource,
    private val albumAdminDataSource: AlbumAdminDataSource,
    savedStateHandle: SavedStateHandle
): ViewModel() {

    val type: Int = savedStateHandle["type"] ?: SELECT_ARTIST

    // 初始化歌手列表页的分页库
    val artistListFlow = Pager(
        PagingConfig(pageSize = 30)
    ){
        return@Pager when(type){
            SELECT_ARTIST ->{
                ArtistPagingSource(adminCore,artistAdminDataSource)
            }
            SELECT_MUSIC ->{
                ArtistPagingSource(adminCore,artistAdminDataSource)
            }
            SELECT_ALBUM ->{
                AlbumPagingSource(adminCore,albumAdminDataSource)
            }
            else ->{
                ArtistPagingSource(adminCore,artistAdminDataSource)
            }
        }
    }.flow.map {
        it.map { data ->
            when (data) {
                is ArtistVO -> {
                    SelectInfo(data.id,data.name,data.imgUrl)
                }
                is AlbumVO -> {
                    SelectInfo(data.id,data.name,data.imgUrl)
                }
                else -> {
                    SelectInfo("","","")
                }
            }
        }
    }.cachedIn(viewModelScope)
        .flowOn(Dispatchers.IO)

}